﻿using KPIS.GERP.ESS.APP.App_UI.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class ESS_MoneyRequestMulti : System.Web.UI.Page
    {
        Main main = new Main();
        FIM_MAS_Contacts.FIM_MAS_Contacts contact = new FIM_MAS_Contacts.FIM_MAS_Contacts();
        BGM_ProjectOperation.BGM_ProjectOperation po = new BGM_ProjectOperation.BGM_ProjectOperation();
        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense ope = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
        BGM_ProjectOperationReport.BGM_ProjectOperationReport rpt = new BGM_ProjectOperationReport.BGM_ProjectOperationReport();
        BGM_MAS_Source.BGM_MAS_Source source = new BGM_MAS_Source.BGM_MAS_Source();
        BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup expGrp = new BGM_MAS_ExpenseGroup.BGM_MAS_ExpenseGroup();
        FIM_MoneyRequests.FIM_MoneyRequests req = new FIM_MoneyRequests.FIM_MoneyRequests();
        FIM_MoneyRequestDtls.FIM_MoneyRequestDtls reqDtls = new FIM_MoneyRequestDtls.FIM_MoneyRequestDtls();
        List<FIM_MAS_Contacts.M_FIM_MAS_Contacts> contacts = new List<FIM_MAS_Contacts.M_FIM_MAS_Contacts>();

        public Dictionary<string, string> expenses
        {
            get
            {
                return (Dictionary<string, string>)(Session["expenses"]);
            }
            set
            {
                Session["expenses"] = value;
            }
        }

        public int count
        {
            get
            {
                return (int)Session["count"];
            }
            set
            {
                Session["count"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                expenses = null;
                count = 0;
                LoadDefault();
                LoadDDLBgmSourceSeq();
                LoadDDLBgmProjOperSeq();
                LoadDDLBgmExpGrpSeq();

                divConfirm.Visible = true;
                divAddRecord.Visible = false;
                divSave.Visible = false;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (expenses != null)
            {
                Table table = CreateTable();
                for (int i = 0; i < count; i++)
                {
                    AddNewRecord(table);
                }
            }
        }

        protected void LoadDefault()
        {
            int year = main.GetSystemControls().default_bgm_year.Value;
            txtBgmYear.Text = year.ToString();
            txtBgmYear.MinValue = year;
            txtBgmYear.MaxValue = year + 1;

            lblMoneyReqDate.Text = DateTime.Today.ToShortDateString();
        }

        protected void LoadDDLBgmSourceSeq()
        {
            var data = source.GetList();
            ddlBgmSourceSeq.DataSource = data;
            ddlBgmSourceSeq.DataBind();

            ddlBgmProjOperSeq.SelectedIndex = 0;
        }

        protected void LoadDDLBgmProjOperSeq()
        {
            ddlBgmProjOperSeq.DataSource = po.GetProjectListByEmpSeq(txtBgmYear.Text, ddlBgmSourceSeq.SelectedValue, SsMng.EmpSeq);
            ddlBgmProjOperSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlBgmProjOperSeq);
            ddlBgmProjOperSeq.SelectedIndex = 0;
        }

        protected void LoadDDLBgmExpGrpSeq()
        {
            ddlBgmExpGrpSeq.DataSource = expGrp.GetList(null);
            ddlBgmExpGrpSeq.DataBind();

            ddlBgmExpGrpSeq.SelectedIndex = 3;
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            LoadDDLBgmProjOperSeq();
        }

        protected void ddlBgmSourceSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLBgmProjOperSeq();
        }

        protected void ddlBgmProjOperSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strBgmProjOperName = ddlBgmProjOperSeq.Text;

            if (ddlBgmProjOperSeq.SelectedIndex > 0)
            {
                txtMoneyReqName.Text = strBgmProjOperName;
            }
            else
            {
                txtMoneyReqName.Text = "";
            }

            LoadGrdMoneyRequestDtls();
        }

        protected void ddlBgmExpGrpSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadGrdMoneyRequestDtls();
        }

        protected void cmdConfirm_Click(object sender, EventArgs e)
        {
            if (grdMoneyRequestDtls.SelectedItems.Count > 0 || txtBgmYear.Text.Length == 4 || !string.IsNullOrEmpty(txtMoneyReqName.Text)
                || !string.IsNullOrEmpty(ddlBgmProjOperSeq.SelectedValue))
            {
                divConfirm.Visible = false;
                divAddRecord.Visible = true;
                divSave.Visible = true;
                txtBgmYear.Enabled = false;
                ddlBgmSourceSeq.Enabled = false;
                ddlBgmProjOperSeq.Enabled = false;
                txtMoneyReqName.Enabled = false;
                ddlBgmExpGrpSeq.Enabled = false;
                grdMoneyRequestDtls.Enabled = false;
                cmdSave.Visible = true;

                expenses = new Dictionary<string, string>();

                foreach (GridDataItem item in grdMoneyRequestDtls.SelectedItems)
                {
                    expenses.Add(main.WebString(item["m_bgm_projectoperationexpense.bgm_proj_oper_exp_seq"].Text)
                        , main.WebString(item["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name"].Text));
                }

                panelExpense.Controls.Clear();
                AddNewRecord(CreateTable());
                count = 1;
            }
            else
            {
                main.MessageAlert(Page, "ข้อมูลไม่ครบถ้วน กรุณากรอกข้อมูลให้ถูกต้อง");
            }
        }

        protected Table CreateTable()
        {
            contacts = contact.GetList(null).ToList();

            Table table = new Table { ID = "tableExpense", CssClass = "tableStyle" };
            TableHeaderRow row = new TableHeaderRow();
            row.Cells.Add(new TableCell { Text = "ผู้ติดต่อ/ผู้รับเงิน", CssClass = "tableStyleHeader" });

            foreach (var expense in expenses)
            {
                row.Cells.Add(new TableCell { Text = expense.Value, CssClass = "tableStyleHeader", Width = 112 });
            }

            row.Cells.Add(new TableCell { Text = "รวม", CssClass = "tableStyleHeader", Width = 112 });

            table.Rows.Add(row);
            panelExpense.Controls.Add(table);

            return table;
        }

        protected void AddNewRecord(Table table)
        {
            cmdAddRecord.Visible = true;

            int index = table.Rows.Count;
            string ID = index.ToString();
            TableRow row = new TableRow();
            row.ID = ID;

            RadComboBox ddlContact = new RadComboBox
            {
                ID = "ddlContact" + ID,
                DataTextField = "contact_name",
                DataValueField = "contact_seq",
                Filter = RadComboBoxFilter.Contains,
                DataSource = contacts,
                Width = 250,
                Height = 200,
            };
            ddlContact.DataBind();

            TableCell cell = new TableCell { VerticalAlign = VerticalAlign.Top };
            cell.Controls.Add(ddlContact);
            row.Cells.Add(cell);

            foreach (var expense in expenses)
            {
                TableCell amountCell = new TableCell { VerticalAlign = VerticalAlign.Top, Width = 112, HorizontalAlign = HorizontalAlign.Right };
                Label lblOperExpenseSeq = new Label { ID = "lblOperExpenseSeq_" + expense.Key + "_" + ID, Text = expense.Key, Visible = false };
                RadNumericTextBox txtAmount = new RadNumericTextBox
                {
                    ID = "txtAmount_" + expense.Key + "_" + ID,
                    AutoPostBack = true,
                    Width = 110,
                    CssClass = "NumericTextBox",
                    EmptyMessage = "จำนวนเงินรวม Vat",
                };
                txtAmount.NumberFormat.DecimalDigits = 2;
                txtAmount.NumberFormat.GroupSeparator = ",";
                txtAmount.TextChanged += AmountTextChanged;

                RadNumericTextBox txtVatPercent = new RadNumericTextBox
                {
                    ID = "txtVatPercent_" + expense.Key + "_" + ID,
                    AutoPostBack = true,
                    Width = 110,
                    CssClass = "NumericTextBox",
                    EmptyMessage = "% Vat",
                };
                txtVatPercent.NumberFormat.DecimalDigits = 2;
                txtVatPercent.NumberFormat.GroupSeparator = ",";
                txtVatPercent.TextChanged += VatPercentTextChanged;

                RadNumericTextBox txtVatAmount = new RadNumericTextBox
                {
                    ID = "txtVatAmount_" + expense.Key + "_" + ID,
                    AutoPostBack = true,
                    Width = 110,
                    CssClass = "NumericTextBox",
                    EmptyMessage = "จำนวนเงิน Vat",
                };
                txtVatAmount.NumberFormat.DecimalDigits = 2;
                txtVatAmount.NumberFormat.GroupSeparator = ",";
                txtVatAmount.TextChanged += VatAmountTextChanged;

                RadNumericTextBox txtExcludeVatAmount = new RadNumericTextBox
                {
                    ID = "txtExcludeVatAmount_" + expense.Key + "_" + ID,
                    AutoPostBack = true,
                    Width = 110,
                    CssClass = "NumericTextBox",
                    EmptyMessage = "จำนวนเงินไม่รวม Vat",
                };
                txtExcludeVatAmount.NumberFormat.DecimalDigits = 2;
                txtExcludeVatAmount.NumberFormat.GroupSeparator = ",";
                txtExcludeVatAmount.TextChanged += IncludeVatTextChanged;

                RadNumericTextBox txtTaxPercent = new RadNumericTextBox
                {
                    ID = "txtTaxPercent_" + expense.Key + "_" + ID,
                    AutoPostBack = true,
                    Width = 110,
                    CssClass = "NumericTextBox",
                    EmptyMessage = "% WH Tax",
                };
                txtTaxPercent.NumberFormat.DecimalDigits = 2;
                txtTaxPercent.NumberFormat.GroupSeparator = ",";
                txtTaxPercent.TextChanged += TaxPercentTextChanged;

                RadNumericTextBox txtTaxAmount = new RadNumericTextBox
                {
                    ID = "txtTaxAmount_" + expense.Key + "_" + ID,
                    AutoPostBack = true,
                    Width = 110,
                    CssClass = "NumericTextBox",
                    EmptyMessage = "จำนวนเงิน WH Tax",
                };
                txtTaxAmount.NumberFormat.DecimalDigits = 2;
                txtTaxAmount.NumberFormat.GroupSeparator = ",";
                txtTaxAmount.TextChanged += TaxAmountTextChanged;

                Label lblNetAmount = new Label { ID = "lblNetAmount_" + expense.Key + "_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red };

                amountCell.Controls.Add(lblOperExpenseSeq);
                amountCell.Controls.Add(txtAmount);
                amountCell.Controls.Add(txtVatPercent);
                amountCell.Controls.Add(txtVatAmount);
                amountCell.Controls.Add(new LiteralControl("<hr style='border-bottom:solid 1px; border-top:none' />"));
                amountCell.Controls.Add(txtExcludeVatAmount);
                amountCell.Controls.Add(new LiteralControl("<hr style='border-bottom:solid 1px; border-top:none' />"));
                amountCell.Controls.Add(txtTaxPercent);
                amountCell.Controls.Add(txtTaxAmount);
                amountCell.Controls.Add(new LiteralControl("<hr style='border-bottom:double 3px; border-top:none' />"));
                amountCell.Controls.Add(lblNetAmount);

                row.Cells.Add(amountCell);
            }

            TableCell sumCell = new TableCell { VerticalAlign = VerticalAlign.Top, Width = 112, HorizontalAlign = HorizontalAlign.Right };
            Label lblSumAmount = new Label { ID = "lblSumAmount_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };
            Label lblSumVatPercent = new Label { ID = "lblSumVatPercent_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };
            Label lblSumVatAmount = new Label { ID = "lblSumVatAmount_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };
            Label lblSumIncludeVatAmount = new Label { ID = "lblSumIncludeVatAmount_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };
            Label lblSumTaxPercent = new Label { ID = "lblSumTaxPercent_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };
            Label lblSumTaxAmount = new Label { ID = "lblSumTaxAmount_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };
            Label lblSumNetAmount = new Label { ID = "lblSumNetAmount_" + ID, Text = "0.00", ForeColor = System.Drawing.Color.Red, Height = 22 };

            sumCell.Controls.Add(lblSumAmount);
            sumCell.Controls.Add(new LiteralControl("<br/>"));
            sumCell.Controls.Add(lblSumVatPercent);
            sumCell.Controls.Add(new LiteralControl("<br/>"));
            sumCell.Controls.Add(lblSumVatAmount);
            sumCell.Controls.Add(new LiteralControl("<hr style='border-bottom:solid 1px; border-top:none' />"));
            sumCell.Controls.Add(lblSumIncludeVatAmount);
            sumCell.Controls.Add(new LiteralControl("<hr style='border-bottom:solid 1px; border-top:none' />"));
            sumCell.Controls.Add(lblSumTaxPercent);
            sumCell.Controls.Add(new LiteralControl("<br/>"));
            sumCell.Controls.Add(lblSumTaxAmount);
            sumCell.Controls.Add(new LiteralControl("<hr style='border-bottom:double 3px; border-top:none' />"));
            sumCell.Controls.Add(lblSumNetAmount);
            row.Cells.Add(sumCell);

            table.Rows.Add(row);
        }

        protected void AmountTextChanged(object sender, EventArgs e)
        {
            CalculateAmount(((RadNumericTextBox)sender).ID, 1);
        }

        protected void VatPercentTextChanged(object sender, EventArgs e)
        {
            CalculateAmount(((RadNumericTextBox)sender).ID, 2);
        }

        protected void VatAmountTextChanged(object sender, EventArgs e)
        {
            CalculateAmount(((RadNumericTextBox)sender).ID, 3);
        }

        protected void IncludeVatTextChanged(object sender, EventArgs e)
        {
            CalculateAmount(((RadNumericTextBox)sender).ID, 4);
        }

        protected void TaxPercentTextChanged(object sender, EventArgs e)
        {
            CalculateAmount(((RadNumericTextBox)sender).ID, 5);
        }

        protected void TaxAmountTextChanged(object sender, EventArgs e)
        {
            CalculateAmount(((RadNumericTextBox)sender).ID, 6);
        }

        protected void CalculateAmount(string ID, int nStep)
        {
            string[] strControlID = ID.Split('_');

            RadNumericTextBox txtAmount = (RadNumericTextBox)panelExpense.FindControl("tableExpense").FindControl("txtAmount_" + strControlID[1] + "_" + strControlID[2]);
            RadNumericTextBox txtVatPercent = (RadNumericTextBox)panelExpense.FindControl("tableExpense").FindControl("txtVatPercent_" + strControlID[1] + "_" + strControlID[2]);
            RadNumericTextBox txtVatAmount = (RadNumericTextBox)panelExpense.FindControl("tableExpense").FindControl("txtVatAmount_" + strControlID[1] + "_" + strControlID[2]);
            RadNumericTextBox txtTaxPercent = (RadNumericTextBox)panelExpense.FindControl("tableExpense").FindControl("txtTaxPercent_" + strControlID[1] + "_" + strControlID[2]);
            RadNumericTextBox txtTaxAmount = (RadNumericTextBox)panelExpense.FindControl("tableExpense").FindControl("txtTaxAmount_" + strControlID[1] + "_" + strControlID[2]);
            RadNumericTextBox txtExcludeVatAmount = (RadNumericTextBox)panelExpense.FindControl("tableExpense").FindControl("txtExcludeVatAmount_" + strControlID[1] + "_" + strControlID[2]);
            Label lblNetAmount = (Label)panelExpense.FindControl("tableExpense").FindControl("lblNetAmount_" + strControlID[1] + "_" + strControlID[2]);

            double dAmount = main.ConvertNullDouble(txtAmount.Text) ?? 0;
            double dPercentVat = main.ConvertNullDouble(txtVatPercent.Text) ?? 0;
            double dPercentTax = main.ConvertNullDouble(txtTaxPercent.Text) ?? 0;
            double dAmountVat = main.ConvertNullDouble(txtVatAmount.Text) ?? 0;
            double dAmountTax = main.ConvertNullDouble(txtTaxAmount.Text) ?? 0;
            double dExcludeVatAmount = main.ConvertNullDouble(txtExcludeVatAmount.Text) ?? 0;
            double dNetAmount = main.ConvertNullDouble(lblNetAmount.Text) ?? 0;

            switch (nStep)
            {
                case 1 :
                case 2 :
                    if (dPercentVat > 0)
                    {
                        dAmountVat = dAmount * 7 / (100 + dPercentVat);//dAmount * dPercentVat / 100;
                    }
                    else
                    {
                        dAmountVat = 0;
                    }
                    dExcludeVatAmount = dAmount - dAmountVat;

                    dAmountTax = dExcludeVatAmount * dPercentTax / 100;
                    dNetAmount = dAmount;
                    break;
                case 3 :
                    dExcludeVatAmount = dAmount - dAmountVat;

                    dAmountTax = dExcludeVatAmount * dPercentTax / 100;
                    dNetAmount = dAmount;
                    break;
                case 4 :
                    dAmountVat = dAmount - dExcludeVatAmount;

                    dAmountTax = dExcludeVatAmount * dPercentTax / 100;
                    dNetAmount = dAmount;
                    break;
                case 5 :
                case 6 :
                    dAmountTax = dExcludeVatAmount * dPercentTax / 100;
                    dNetAmount = dAmount;
                    break;
            }

            txtVatAmount.Text = dAmountVat.ToString("#,##0.00");
            txtTaxAmount.Text = dAmountTax.ToString("#,##0.00");
            txtExcludeVatAmount.Text = dExcludeVatAmount.ToString("#,##0.00");
            lblNetAmount.Text = dNetAmount.ToString("#,##0.00");

            SumAmount(ID);
        }

        protected void SumAmount(string ID)
        {
            string[] strControlID = ID.Split('_');

            double dSumAmount = 0;
            double dSumVatPercent = 0;
            double dSumVatAmount = 0;
            double dSumIncludeVatAmount = 0;
            double dSumTaxPercent = 0;
            double dSumTaxAmount = 0;
            double dSumNetAmount = 0;

            Label lblSumAmount = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumAmount_" + strControlID[2]);
            Label lblSumVatPercent = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumVatPercent_" + strControlID[2]);
            Label lblSumVatAmount = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumVatAmount_" + strControlID[2]);
            Label lblSumIncludeVatAmount = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumIncludeVatAmount_" + strControlID[2]);
            Label lblSumTaxPercent = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumTaxPercent_" + strControlID[2]);
            Label lblSumTaxAmount = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumTaxAmount_" + strControlID[2]);
            Label lblSumNetAmount = (Label)panelExpense.FindControl("tableExpense").FindControl("lblSumNetAmount_" + strControlID[2]);

            TableRow row = (TableRow)lblSumAmount.Parent.Parent;

            for (int i = 0; i < row.Controls.Count - 1; i++)
            {
                if (i != 0)
                {
                    TableCell cell = (TableCell)row.Controls[i];
                    dSumAmount += ((RadNumericTextBox)cell.Controls[1]).Value ?? 0;
                    dSumVatPercent += ((RadNumericTextBox)cell.Controls[2]).Value ?? 0;
                    dSumVatAmount += ((RadNumericTextBox)cell.Controls[3]).Value ?? 0;
                    dSumIncludeVatAmount += ((RadNumericTextBox)cell.Controls[5]).Value ?? 0;
                    dSumTaxPercent += ((RadNumericTextBox)cell.Controls[7]).Value ?? 0;
                    dSumTaxAmount += ((RadNumericTextBox)cell.Controls[8]).Value ?? 0;
                    dSumNetAmount += main.ConvertNullDouble(((Label)cell.Controls[10]).Text) ?? 0;
                }
            }

            lblSumAmount.Text = dSumAmount.ToString("#,##0.00");
            lblSumVatPercent.Text = dSumVatPercent.ToString("#,##0.00");
            lblSumVatAmount.Text = dSumVatAmount.ToString("#,##0.00");
            lblSumIncludeVatAmount.Text = dSumIncludeVatAmount.ToString("#,##0.00");
            lblSumTaxPercent.Text = dSumTaxPercent.ToString("#,##0.00");
            lblSumTaxAmount.Text = dSumTaxAmount.ToString("#,##0.00");
            lblSumNetAmount.Text = dSumNetAmount.ToString("#,##0.00");
        }

        protected void LoadGrdMoneyRequestDtls()
        {
            IList<FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls> models = null;
            if (!string.IsNullOrEmpty(ddlBgmProjOperSeq.SelectedValue) && !string.IsNullOrEmpty(ddlBgmSourceSeq.SelectedValue) && !string.IsNullOrEmpty(ddlBgmExpGrpSeq.SelectedValue))
            {
                models = reqDtls.GetExpFromProject(ddlBgmProjOperSeq.SelectedValue
                    , ddlBgmSourceSeq.SelectedValue, ddlBgmExpGrpSeq.SelectedValue, null);
            }
            else
            {
                models = new List<FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls>();
            }

            grdMoneyRequestDtls.DataSource = models;

            GridGroupByExpression group1 = new GridGroupByExpression(grdMoneyRequestDtls.Columns.FindByUniqueName("m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_name"));
            GridGroupByExpression group2 = new GridGroupByExpression(grdMoneyRequestDtls.Columns.FindByUniqueName("m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_name"));

            grdMoneyRequestDtls.MasterTableView.GroupByExpressions.Add(group2);
            grdMoneyRequestDtls.MasterTableView.GroupByExpressions.Add(group1);
            grdMoneyRequestDtls.DataBind();
        }

        protected void cmdAddRecord_Click(object sender, EventArgs e)
        {
            Table table = (Table)panelExpense.FindControl("tableExpense");

            if (table != null)
            {
                count++;
                AddNewRecord(table);
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            int nEmpSeq = SsMng.EmpSeqI;
            var report = rpt.GetFull(ddlBgmProjOperSeq.SelectedValue, null, null).ToList();
            double dRemainAmount = report.Sum(o => o.cal_amount) ?? 0;
            double dRequestAmount = 0;
            Table tb = (Table)panelExpense.FindControl("tableExpense");
            
            foreach (TableRow tr in tb.Rows)
            {
                if (tr.ID != null)
                {
                    if (string.IsNullOrEmpty(((RadComboBox)tr.FindControl("ddlContact" + tr.ID)).SelectedValue))
                    {
                        main.MessageAlert(Page, "กรุณาเลือกผู้ติดต่อ/ผู้รับเงินให้ครบถ้วน!!");
                        return;
                    }

                    dRequestAmount += main.ConvertNullDouble(((Label)tr.FindControl("lblSumNetAmount_" + tr.ID)).Text) ?? 0;
                }
            }

            if (dRemainAmount < dRequestAmount)
            {
                main.MessageAlert(Page, "จำนวนเงินที่ขอเกินกว่าเงินที่ได้รับอนุมัติ!!");
                return;
            }

            foreach (TableRow tr in tb.Rows)
            {
                if (tr.ID != null)
                {
                    string strContactSeq = ((RadComboBox)tr.FindControl("ddlContact" + tr.ID)).SelectedValue;
                    FIM_MoneyRequests.M_FIM_MoneyRequests info = new FIM_MoneyRequests.M_FIM_MoneyRequests();
                    info.bgm_source_seq = main.ConvertNullInt(ddlBgmSourceSeq.SelectedValue);
                    info.bgm_year = main.ConvertNullInt(txtBgmYear.Text);
                    info.bgm_exp_grp_seq = main.ConvertNullInt(ddlBgmExpGrpSeq.SelectedValue);
                    info.work_area_seq = 1;
                    info.event_seq = 12;
                    info.money_req_date = main.ConvertNullDateTime(lblMoneyReqDate.Text);
                    info.use_advance = "0";
                    info.advance_bgm_source_seq = null;
                    string refNo = req.GenerateNextMoneyRequestRefNo(ddlBgmSourceSeq.SelectedValue == "1" ? "1" : "2");
                    if (string.IsNullOrEmpty(refNo))
                    {
                        if (string.IsNullOrEmpty(refNo = req.GenerateNextMoneyRequestRefNo(ddlBgmSourceSeq.SelectedValue == "1" ? "1" : "2")))
                        {
                            if (string.IsNullOrEmpty(refNo = req.GenerateNextMoneyRequestRefNo(ddlBgmSourceSeq.SelectedValue == "1" ? "1" : "2")))
                            {
                                throw new Exception("Cannot generate refno (null)");
                            }
                        }
                    }
                    info.ref_no = refNo;
                    info.doc_ref_no = null;
                    info.money_req_name = txtMoneyReqName.Text;
                    info.money_req_name_plus = "";
                    info.bgm_proj_oper_seq = main.ConvertNullInt(ddlBgmProjOperSeq.SelectedValue);
                    info.emp_seq = nEmpSeq;
                    info.job_site_seq = SsMng.WorkingJobSiteSeqI;
                    info.contact_seq = main.ConvertNullInt(strContactSeq);
                    info.icm_dn_seq = null;
                    info.approver_seq = null;
                    info.allow = "0";

                    info.created_by = nEmpSeq;
                    info.created_when = DateTime.Now;

                    string strMoneyReqSeq = req.Insert(info);

                    for (int i = 1; i < tr.Controls.Count - 1; i++)
                    {
                        TableCell cell = tr.Cells[i];

                        if ((main.ConvertNullDouble(((Label)cell.Controls[10]).Text) ?? 0) > 0)
                        {
                            var dtlsInfo = new FIM_MoneyRequestDtls.M_FIM_MoneyRequestDtls();
                            dtlsInfo.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
                            dtlsInfo.bgm_proj_oper_exp_seq = Convert.ToInt32(((RadNumericTextBox)cell.Controls[2]).ID.Split('_')[1]);
                            dtlsInfo.percent_vat = ((RadNumericTextBox)cell.Controls[2]).Value ?? 0;
                            dtlsInfo.amount_vat = ((RadNumericTextBox)cell.Controls[3]).Value ?? 0;
                            dtlsInfo.percent_tax = ((RadNumericTextBox)cell.Controls[7]).Value ?? 0;
                            dtlsInfo.amount_tax = ((RadNumericTextBox)cell.Controls[8]).Value ?? 0;
                            dtlsInfo.amount = main.ConvertNullDouble(((Label)cell.Controls[10]).Text) ?? 0;
                            dtlsInfo.record_status = "W";
                            dtlsInfo.created_by = SsMng.EmpSeqI;
                            dtlsInfo.created_when = DateTime.Now;

                            reqDtls.Insert(dtlsInfo);
                        }
                    }
                }
            }

            expenses = null;
            count = 0;
            LoadDefault();
            ddlBgmProjOperSeq.SelectedIndex = 0;
            txtMoneyReqName.Text = "";

            divConfirm.Visible = true;
            divAddRecord.Visible = false;
            divSave.Visible = false;
            main.MessageAlert(Page, "บันทึกเรียบร้อย!!");
        }
    }
}